import { getResourcesList, addResources, updateResources, getSingleResource, deleteResources } from '@/api/auth'
import { getToken } from '@/utils/auth'

const auth = {
  state: {
    resourcesList: [],
    singleItem: {},
    roken: getToken() || ''
  },
  mutations: {
    SET_LIST: (state, data) => {
      state.resourcesList = data
    },
    SET_SINGLE_ITEM: (state, data) => {
      state.singleItem = data
    }
  },
  actions: {
    GetResourcesList: ({ commit, state }) => {
      return new Promise((resolve, reject) => {
        getResourcesList(state.token).then(response => {
          const data = response.data
          if (data && data > 0) { // 验证返回的Resourcess是否是一个非空数组
            commit('SET_LIST', data)
          } else {
            reject('getResourceslistFailed: list must be a non-null array !')
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    AddResources: ({ state }, params) => {
      return new Promise((resolve, reject) => {
        addResources(state.token, params).then(res => {
          if (res.result === 'success') {
            resolve(res)
          } else {
            reject(res)
          }
        }).catch(err => {
          reject(err)
        })
      })
    },

    UpdateResources: ({ state }, params) => {
      return new Promise((resolve, reject) => {
        updateResources(state.token, params).then(res => {
          if (res.result === 'success') {
            resolve(res)
          } else {
            reject(res)
          }
        }).catch(err => {
          reject(err)
        })
      })
    },

    GetSingleResource: ({ commit, state }, params) => {
      return new Promise((resolve, reject) => {
        getSingleResource(state.token, params).then(res => {
          if (res.result === 'success') {
            commit('SET_SINGLE_ITEM', res.data)
            resolve(res)
          } else {
            reject(res)
          }
        }).catch(err => {
          reject(err)
        })
      })
    },

    DeleteResources: ({ state }, params) => {
      return new Promise((resolve, reject) => {
        deleteResources(state.token, params).then(res => {
          if (res.result === 'success') {
            resolve(res)
          } else {
            reject(res)
          }
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}

export default auth
